<template>
  <div class="player">
    <!-- 头像信息 -->
    <div class="right">
      <div class="upp">
        <img :src="playlist[playlistIndex].al.picUrl"
             alt="">
        <div class="up"
             @click="openDetail">
          <i class=" el-icon-arrow-up "
             style="cursor:pointer;margin-left:15px ;margin-top: 14px;font-size: 25px;color: #fff;"></i>
        </div>
      </div>
      <div class="item">
        <span>{{ playlist[playlistIndex].name}}</span>
        <span style="font-size:13px;"
              v-if="playlist[playlistIndex].ar[0]">{{ playlist[playlistIndex].ar[0].name}}</span>
      </div>
    </div>
    <div class="play">
      <!-- 播放按钮 -->
      <div class="header">
        <div class="player-bar">
          <button>
            <i class="iconfont icon-liebiaoshunxu"
               @click="Download"></i>
          </button>
          <button>
            <i class="iconfont icon-shangyishou"
               @click="goPlay(-1)"></i>
          </button>
          <button @click="play"
                  class="zanting">
            <i v-if="!isBtnShow"
               class="iconfont icon-zanting"></i>
            <i v-else
               class="iconfont icon-bofang"></i>
          </button>
          <button>
            <i class="iconfont icon-xiayishou"
               @click="goPlay(1)"></i>
          </button>
          <button class="player-bar-btn"
                  @click="likeMusic">
            <i v-show="!isLiked"
               class="iconfont icon-aixin"></i>
            <i v-show="isLiked"
               style="color: #ec4141"
               class="iconfont icon-aixin1"></i>
          </button>
        </div>
      </div>
      <!-- 进度条 -->
      <div class="button">
        <!-- <span class="font-12">{{
            formatDateTime(currentTime)}}</span>
        <input type="range"
               class="timeSlider"
               min="0"
               :max=" duration"
               v-model="currentTime"
               step="0.08">
        <span class="font-12">{{
         formatDateTime(duration)}}</span> -->
        <span class="font-12">{{
            currentTime|formatDateTime}}</span>
        <el-slider v-model="curren"
                   :percentage="curren"
                   class="timeSlider"
                   :show-tooltip="false"
                   :max="duration"
                   :min="0"
                   @change="changeCurrenTime"
                   :disabled=" songUrl == ''"></el-slider>
        <span class="font-12">{{
            duration|formatDateTime}}</span>
      </div>
    </div>
    <!-- 音乐详情界面 -->
    <div class="detail"
         v-show="detailShow">
      <el-drawer :visible.sync="detailShow"
                 direction="btt"
                 size="100%"
                 :modal="false"
                 :show-close="false"
                 :before-close="handleClose"
                 style="position:absolute;bottom:80px;left: 0;">
        <img v-lazy="playlist[playlistIndex].al.picUrl"
             alt=""
             style="position:absolute;width: 100%;height: 40%;filter: blur(200px);">
        <!--背景虚化-->
        <template #title>
          <div>
            <i class="el-icon-arrow-down pointer"
               @click="detailShow = false"
               style="cursor:pointer"></i>
          </div>
        </template>
        <MusicDetail :MusicDetail=" playlist[playlistIndex]"
                     :isBtnShow="isBtnShow"
                     :Lyrics="Lyrics"></MusicDetail>
      </el-drawer>
    </div>
    <audio ref="audio"
           :src="songUrl"></audio>
  </div>
</template>
<script>
import { getDownload } from "@/api/author"
import { getLike } from "@/api/User"
import MusicDetail from "@/components/MusicDetail"
import { getSongUrl, getLyric } from '@/api/RankList'
import { mapState, mapMutations } from 'vuex';
export default {
  name: 'Player',
  data () {
    return {
      songUrl: '',
      detailShow: false,
      Lyrics: {},//歌词
      interVal: 0,//当前时间
      curren: 0,
    }
  },
  components: { MusicDetail },
  computed: {
    ...mapState({
      playlist: (state) => {
        return state.playlist.playlist;
      },
      playlistIndex: (state) => {
        return state.playlist.playlistIndex;
      },
      isBtnShow: (state) => {
        return state.playlist.isBtnShow;
      },
      currentTime: (state) => {
        return state.playlist.currentTime;
      },
      duration: (state) => {
        return state.playlist.duration;
      },
      likeList: (state) => {
        return state.user.likeList
      },
      musicId: (state) => {
        return state.playlist.musicId
      },
    }),
    isLiked: {
      get () {
        return this.likeList.indexOf(this.musicId) !== -1
      },
      set (val) {
        if (this.isLiked) {
          this.$store.commit('setLikeList', {
            type: 'remove',
            data: val
          })
        } else {
          this.$store.commit('setLikeList', {
            type: 'unshift',
            data: val
          })
        }
      }
    }
  },
  mounted () {
    //全局事件总线
    this.$bus.$on('currentId', (id) => {
      console.log('我是player，收到了ItemList传过来的数据', id)
      this.getMusicUrl(id)
      this.getLyrics(id)//获取歌词
      this.updataTime()//播放就触发函数进行传值
    })

  },
  updated () {
    this.updatedDuration(this.$refs.audio.duration)//歌曲总时长
  },
  beforeDestroy () {
    this.$bus.$off('currentId');//用完后记得顺手丢掉销毁哦
  },
  methods: {
    // 下载音乐
    async Download () {
      if (this.songUrl == '') return
      let res = await getDownload(this.musicId)
    },
    // 播放
    play: function () {
      if (this.$refs.audio.paused) {
        //播放音乐
        this.$refs.audio.play()
        //暂停图标隐藏
        this.updatedisBtnShow(false)
        this.updataTime()//播放就触发函数进行传值
      } else {
        //音乐暂停
        this.$refs.audio.pause()
        this.updatedisBtnShow(true)
        // 清除定时器
        clearInterval(this.interVal)//暂停清除定时器
      }
    },
    // 更新当前时间，以实现歌词逐句显示以及歌词进度条的时间显示
    updataTime: function () {
      this.interVal = setInterval(() => {
        this.$store.commit('updatedCurrentTime', this.$refs.audio.currentTime)
        this.curren = this.currentTime
      }, 1000)
    },
    // 手动拖动进度条回调
    changeCurrenTime (val) {
      this.$refs.audio.currentTime = val
    },
    /* 喜欢音乐 */
    async likeMusic () {
      var isLogin = JSON.parse(localStorage.getItem('isLogin'))
      if (!isLogin) return this.$message.warning('需要登录')
      if (this.musicId === 0 || typeof this.musicId === 'undefined')
        return
      const res = await getLike(this.musicId, !this.isLiked)
      if (res.code !== 200) return
      this.$message.success(`${this.isLiked ? '取消喜欢' : '喜欢'}成功`)
      this.isLiked = this.musicId
    },
    // 获取音乐url
    async getMusicUrl (id) {
      let res = await getSongUrl(id)
      this.songUrl = res.data[0].url
    },
    ...mapMutations(['updatedisBtnShow', 'updatedCurrentTime', 'updatedPlaylistIndex', 'updatedDuration', 'upMusicId', 'setLikeList']),
    // 打开音乐详情界面
    openDetail () {
      this.detailShow = !this.detailShow
    },
    // 歌曲详情界面显示
    handleClose () {
      this.detailShow = false
    },
    // 获取歌词
    async getLyrics (value) {
      let res = await getLyric(value)
      if (res.code !== 200) return
      this.Lyrics = res.lrc
    },
    // 歌曲切换
    goPlay (val) {
      let index = this.playlistIndex + val
      if (index < 0) {
        index = this.playlist.length - 1
      } else if (index = this.playlistIndex.length - 1) {
        index = 0
      } else {
        index = this.playlistIndex + val
      }
      this.updatedPlaylistIndex(index)//传入index实现改变下标来切换歌曲
      this.getMusicUrl(this.playlist[index].id)//获取歌曲url
      this.$store.commit('upMusicId', this.playlist[index].id)
      this.getLyrics(this.playlist[index].id)//获取歌词
    },
  },
  watch: {
    musicId () {//如果下标发生变化，就自动播放音乐
      this.$refs.audio.autoplay = true;
      if (this.$refs.audio.paused) {//如果是暂停状态，改变图标
        this.updatedisBtnShow(false)
      }
    },
    playlist () {//如果播放列表发生改变，自动播放
      if (this.isBtnShow) {
        this.$refs.audio.autoplay = true;
        this.updatedisBtnShow(false)
      }
    },
    // 实现自动播放歌曲
    currentTime (newValue) {
      if (newValue === this.duration) {
        // 判断是否最后一首，如果是就是改变下标为零
        if (this.playlistIndex === this.playlist.length - 1) {
          this.updatedPlaylistIndex(0)
          this.play()
        } else {
          this.updatedPlaylistIndex(this.playlistIndex + 1)
        }
        this.getMusicUrl(this.playlist[this.playlistIndex].id)//获取歌曲url
        this.getLyrics(this.playlist[this.playlistIndex].id)//获取歌词
        this.$store.commit('upMusicId', this.playlist[this.playlistIndex].id)
      }
    }
  },
}
</script>

<style scoped lang="less">
.player {
  width: 1536px;
  height: 80px;
  border-top: 1px solid #e0e0e0;
  .right {
    float: left;
    width: 340px;
    height: 70px;
    position: relative;
    .upp {
      &:hover .up {
        display: block;
      }
      img {
        display: block;
        float: left;
        border-radius: 5px;
        width: 55px;
        height: 55px;
        margin: 15px;
        cursor: pointer;
      }
      .up {
        display: none;
        position: absolute;
        width: 55px;
        height: 55px;
        margin: 15px;
        border-radius: 5px;
        background-color: rgb(83, 81, 81);
        opacity: 0.6;
      }
    }
    .item {
      float: left;
      width: 90px;
      height: 50px;
      margin-top: 10px;

      span {
        overflow: hidden;
        display: block;
        font-size: 16px;
        height: 25px;
        font-weight: lighter;
        line-height: 30px;
      }
    }
    .icono {
      float: left;
      .cc {
        margin-left: 5px;
        margin-top: 14px;
        width: 20px;
        height: 20px;
      }
    }
  }
  .play {
    margin-left: 33%;
    width: 500px;
    height: 60px;
    overflow: hidden;
    margin-top: 10px;
    position: relative;
    .header {
      .player-bar {
        width: 300px;
        margin: 0 auto;
        display: flex;
        align-items: center;
        margin-top: 6px;
        justify-content: space-around;
        button,
        div {
          outline: none;
          border: none;
          background-color: #fff;
          cursor: pointer;
          .iconfont {
            font-size: 18px;
          }

          &:nth-child(3) {
            height: 32px;
            width: 32px;
            border-radius: 50%;
            background-color: #f4f4f4;
            display: flex;
            align-items: center;
            justify-content: center;
            .iconfont {
              font-size: 16px;
            }
          }

          &:hover {
            transition: 0s;
            color: red;
          }

          &:nth-child(3):hover {
            background-color: #e5e5e5;
          }
        }
      }
    }
    .button {
      display: flex;
      align-items: center;
      position: absolute;
      top: 30px;
      left: 0px;
      .font-12 {
        width: 30px;
        height: 15px;
        font-size: 12px;
      }
      .timeSlider {
        float: left;
        width: 400px;
        margin: 0 10px;
      }
    }
  }
}
</style>